<?php
namespace lib\db;

use config\config;
use lib\helper\error;
use lib\rule\ParentInit;
/**
 * Ldy-Item-DB(基础类底层基础)
 * DB数据库连接类
 */
class Db extends ParentInit{

    protected static $dbcon=false;
    private $host;
    private $port;
    private $user;
    private $pass;
    private $db;
    private $charset;
    protected $link;

    protected function _init()
    {
        $data = config::get('db');
        $this->host =  $data['host'];
        $this->port =  $data['port'];
        $this->user =  $data['user'];
        $this->pass =  $data['password'];
        $this->db =  $data['db'];
        $this->charset= 'utf8';
        //连接数据库
        $this->db_connect();
        //选择数据库
        $this->db_usedb();
        //设置字符集
        $this->db_charset();
        parent::_init(); // TODO: Change the autogenerated stub
    }

    /**
     * 连接数据库 并且处理 数据库 重复连接问题
     */
    private function db_connect(){
        if(self::$dbcon == false) {
            $this->link = mysqli_connect($this->host . ':' . $this->port, $this->user, $this->pass);
            self::$dbcon = $this->link;
        }else{
             $this->link = self::$dbcon ;
        }
        if(!$this->link){
           error::_plainError($this->link);
        }
    }

    /**
     * 设置字符集
     */
    private function db_charset(){
        mysqli_query($this->link,"set names {$this->charset}");
    }

    /**
     * 选择数据库
     */
    private function db_usedb(){
        mysqli_query($this->link,"use {$this->db}");
    }

    /**
     * 私有的克隆
     */
    private function __clone(){
        die('clone is not allowed');
    }

    /**
     * 执行sql语句的方法
     * @param $sql
     * @return bool|\mysqli_result
     */
    public function query($sql){
        $res=mysqli_query($this->link,$sql);
        if(!$res){
            error::_plainError($this->link);
        }
        return $res;
    }

    /**
     * 获得最后一条记录id
     * @return int|string
     */
    public function getInsertid(){
        return mysqli_insert_id($this->link);
    }


    /**
     * 获取一条记录,前置条件通过资源获取一条记录
     * @param $query
     * @param string $type
     * @return mixed
     */
    public function getFormSource($query,$type="assoc"){
        if(!in_array($type,array("assoc","array","row")))
        {
            die("mysqli_query error");
        }
        $funcname="mysqli_fetch_".$type;
        return $funcname($query);
    }


}
